<template>
  <view class="form-container">
    <u-form :model="formData" ref="uForm">
      <u-form-item v-for="(item, index) in formItems" :key="index" :label="item.label" :prop="item.key">
        <u-input v-if="item.type === 'input'" v-model="formData[item.key]" />
        <u-radio-group v-else-if="item.type === 'radio'" v-model="formData[item.key]">
          <u-radio v-for="(option, idx) in item.options" :key="idx" :label="option.label" :name="option.value"></u-radio>
        </u-radio-group>
        <u-checkbox-group v-else-if="item.type === 'checkbox'" v-model="formData[item.key]">
          <u-checkbox v-for="(option, idx) in item.options" :key="idx" :label="option.label" :name="option.value"></u-checkbox>
        </u-checkbox-group>
        <u-select v-else-if="item.type === 'select'" v-model="formData[item.key]" :list="item.options.map(option => ({ label: option.label, value: option.value }))" />
      </u-form-item>
    </u-form>
    <u-button @click="submitForm">提交</u-button>
  </view>
</template>

<script>
import { ref, onMounted } from 'vue';
import { uForm, uFormItem, uInput, uRadioGroup, uRadio, uCheckboxGroup, uCheckbox, uSelect, uButton } from '@dcloudio/uni-ui';

export default {
  components: {
    uForm,
    uFormItem,
    uInput,
    uRadioGroup,
    uRadio,
    uCheckboxGroup,
    uCheckbox,
    uSelect,
    uButton
  },
  setup() {
    const formData = ref({});
    const formItems = ref([]);

    const loadFormData = async () => {
      // 模拟从后台获取表单项数据
      try {
        const response = await fetch('https://example.com/api/formData');
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        formItems.value = await response.json();
      } catch (error) {
        console.error('Failed to load form data:', error);
      }
    };

    const loadOptionsByDictCode = async (dictCode) => {
      // 模拟从后台获取选项数据
      try {
        const response = await fetch(`https://example.com/api/dict/${dictCode}`);
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return await response.json();
      } catch (error) {
        console.error('Failed to load options by dict code:', error);
        return [];
      }
    };

    const initForm = async () => {
      await loadFormData();
      for (let item of formItems.value) {
        if (['radio', 'checkbox', 'select'].includes(item.type)) {
          item.options = await loadOptionsByDictCode(item.dictCode);
        }
      }
    };

    onMounted(() => {
      initForm();
    });

    const submitForm = () => {
      console.log('提交的数据:', formData.value);
    };

    return {
      formData,
      formItems,
      submitForm
    };
  }
};
</script>

<style scoped>
.form-container {
  padding: 20px;
}
</style>



